package com.rolerealm.controller;

import com.rolerealm.common.result.Result;
import com.rolerealm.common.util.JwtUtil;
import com.rolerealm.common.util.ResultUtil;
import com.rolerealm.domain.dto.ConversationDTOs.ConversationCreateRequest;
import com.rolerealm.domain.dto.ConversationDTOs.ConversationCreateResponse;
import com.rolerealm.domain.dto.ConversationDTOs.MessageRequest;
import com.rolerealm.domain.dto.ConversationDTOs.MessageResponse;
import com.rolerealm.domain.dto.SkillDTOs.SwitchSkillRequest;
import com.rolerealm.domain.vo.ConversationListItemVO;
import com.rolerealm.domain.vo.ConversationMessageVO;
import com.rolerealm.domain.vo.PageResult;
import com.rolerealm.service.ConversationService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/conversations")
@RequiredArgsConstructor
public class ConversationController {

    private final ConversationService conversationService;
    private final JwtUtil jwtUtil;

    @PostMapping
    public Result<ConversationCreateResponse> createConversation(
            @RequestHeader(name = "Authorization", required = false) String authorization,
            @RequestBody @Valid ConversationCreateRequest request) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        Long conversationId = conversationService.createConversation(userId, request);

        ConversationCreateResponse response = ConversationCreateResponse.builder()
                .conversationId(conversationId)
                .build();
        return ResultUtil.success(response);
    }

    @PostMapping("/{conversationId}/messages")
    public Result<MessageResponse> sendMessage(
            @RequestHeader(name = "Authorization", required = false) String authorization,
            @PathVariable Long conversationId,
            @RequestBody @Valid MessageRequest request) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        MessageResponse response = conversationService.sendMessage(conversationId, userId, request);
        return ResultUtil.success(response);
    }

    @PutMapping("/{conversationId}/skill")
    public Result<Void> switchSkill(
            @RequestHeader(name = "Authorization", required = false) String authorization,
            @PathVariable Long conversationId,
            @RequestBody @Valid SwitchSkillRequest request) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        conversationService.switchSkill(conversationId, userId, request.getSkillType());
        return ResultUtil.success();
    }

    /**
     * 会话列表（分页）
     */
    @GetMapping
    public Result<PageResult<ConversationListItemVO>> pageConversations(
            @RequestHeader(name = "Authorization", required = false) String authorization,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long characterId) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        PageResult<ConversationListItemVO> result = conversationService.pageUserConversations(userId, characterId, page, size);
        return ResultUtil.success(result);
    }

    /**
     * 会话消息（分页）
     */
    @GetMapping("/{conversationId}/messages")
    public Result<PageResult<ConversationMessageVO>> pageMessages(
            @RequestHeader(name = "Authorization", required = false) String authorization,
            @PathVariable Long conversationId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        PageResult<ConversationMessageVO> result = conversationService.pageMessages(conversationId, userId, page, size);
        return ResultUtil.success(result);
    }

    /**
     * 删除会话（级联逻辑删除消息）
     */
    @DeleteMapping("/{conversationId}")
    public Result<Void> deleteConversation(
            @RequestHeader(name = "Authorization", required = false) String authorization,
            @PathVariable Long conversationId) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        conversationService.deleteConversation(conversationId, userId);
        return ResultUtil.success();
    }

    /**
     * 清理空对话（删除没有消息的对话）
     */
    @DeleteMapping("/clean-empty")
    public Result<Integer> cleanEmptyConversations(
            @RequestHeader(name = "Authorization", required = false) String authorization) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        int cleanedCount = conversationService.cleanEmptyConversations(userId);
        return ResultUtil.success(cleanedCount);
    }
}


